let { request,connection } = require('../db/mysql')
let md5 = require('md5');
let moment = require('moment')
var svgCaptcha = require('svg-captcha');
let {createToken} = require('../utils/token')
let globalCap =''
exports.UserList= async(req, res)=> {
    // http://localhost:3000/userlist?page=1&size=5&is_show=1&leval=1
      let page = req.query.page || 1;
      let size = req.query.size ||5;
      let leval = req.query.leval || 0;
      let sql;
      let countSql;
      if(leval==0){
        sql = `SELECT * FROM hg_users WHERE is_show=1  ORDER BY id ASC LIMIT ${(page-1)*size},${size}`
        countSql = `SELECT COUNT(*) FROM hg_users WHERE is_show=1`
      }else{
        sql = `SELECT * FROM hg_users WHERE is_show=1 and leval = ${leval} ORDER BY id ASC LIMIT ${(page-1)*size},${size}`
        countSql = `SELECT COUNT(*) FROM hg_users WHERE is_show=1 and leval = ${leval}`
      }
       
      let result = await request(sql)
      let countTotal = await request(countSql)
      
      // console.log('result',result)
      console.log('countTotal',countTotal)
      let count = countTotal[0]['COUNT(*)']
      let pages = Math.ceil(count*1/size)
      res.json({
        status:200,
        msg:'成功',
        page:page*1,
        size:size*1,
        pages:pages,
        count:count,
        data:result
      })
  
  };
  // 注册用户
  exports.UserAdd= async(req, res)=> {
    // 注册规则
    // 先判断该用户在数据库中是否存在
    // 如果存在就让你去登录
    // 如果不存在就可以注册

    // console.log('req',req)
    let { username,leval,is_show } = req.body
    let password = md5(req.body.password)
    let is_Username = `SELECT * FROM hg_users WHERE username="${username}"`
    connection.query(is_Username,  (error, results)=> {
        if(error){
           return res.json({
                status:1001,
                msg:'查询失败'
            })
        }else{
          console.log('results',results)//数组
          if(results.length>0){
            // 证明该用户已存在
            return res.json({
                status:1002,
                msg:'用户已存在，请去登录'
            })
          }else{
            let nowTime = moment().format('YYYY-MM-DD, HH:mm:ss')
            let phone = '15617664372'
            let insertSql = `INSERT INTO hg_users SET username='${username}',password='${password}',leval='${leval}',create_time='${nowTime}',is_show='${is_show}',phone='${phone}'`
            connection.query(insertSql,  (error, results)=> {
              if(error){
                return  res.json({
                  status:1003,
                  msg:'添加失败'
              })
              }else{
                return res.json({
                  status:200,
                  msg:'添加成功',
                  data:results
              })
              }
            });
            
          }
        }
  });

  };
  // 图形验证码
  exports.SvgCaptcha = (req,res)=>{
    var captcha = svgCaptcha.create({
      size: 4, // size of random string
      ignoreChars: '0o1i', // filter out some characters like 0o1i
      noise: 5 ,// number of noise lines
      color: true, // characters will have distinct colors instead of grey, true if background option is set
      background: '#cc9966' // background color of the svg image
    });
    console.log(captcha.text)
    globalCap = captcha.text.toLowerCase()
    res.type('svg');
    res.status(200).send(captcha.data);
  }
  // 登录接口
  exports.login= async(req, res)=> {
    
    let { username,captcha } = req.body
    let password = md5(req.body.password)
    if(globalCap!=captcha.toLowerCase()){
      return  res.json({
          status:1005,
          msg:'验证码错误'
        })
    }
    let is_Username = `SELECT * FROM hg_users WHERE username="${username}"`
    connection.query(is_Username,  (error, results)=> {
        if(error){
          return res.json({
                status:1001,
                msg:'查询失败'
            })
        }else{
          if(results.length>0){
            let is_Username = `SELECT * FROM hg_users WHERE username="${username}" AND password="${password}"`
            // 证明该用户已存在
            connection.query(is_Username,  (error, results)=> {
              if(error){
                return  res.json({
                  status:1003,
                  msg:'查询失败'
              })
              }else{
                if(results.length>0){
                  let token = createToken({
                    username:username
                  })
                  return  res.json({
                      status:200,
                      msg:'登录成功',
                      token:token
                  })
                }else{
                  return  res.json({
                    status:1007,
                    msg:'用户名或密码错误'
                })
                }
                
              }
            });
          }else{
            return  res.json({
              status:1007,
              msg:'用户名不存在'
          })
            
          }
        }
  });

  };
  // 编辑
  exports.userEdit= async(req, res)=> {
  //  只能修改邮箱和年龄
    let editData = req.body
    let is_Username = `UPDATE hg_users SET age='${editData.age}',email='${editData.email}' WHERE id='${editData.id}'`
    let result = await request(is_Username)
    res.json({
      status:200,
      msg:'修改成功',
      data:result
    })

  };
  // 删除
  exports.userDelete= async(req, res)=> {
    //  只能修改邮箱和年龄
      let editData = req.query
      let is_Username = `DELETE FROM hg_users WHERE id='${editData.id}'`
      let result = await request(is_Username)
      res.json({
        status:200,
        msg:'修改成功',
        data:result
      })
  
    };